package com.xinyue.game.service.framwork.context;

import com.alibaba.fastjson.JSON;
import com.xinyue.game.message.GameServerMessageModel;
import com.xinyue.game.message.GameServerRequestHeader;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.StandardCharsets;

public class GameUserChannelContext {
    private static Logger logger = LoggerFactory.getLogger(GameUserChannelContext.class);
    private GameServerMessageModel<GameServerRequestHeader> requestParam;
    private GameUserChannel gameUserChannel;
    private ChannelHandlerContext ctx;


    public GameUserChannelContext(ChannelHandlerContext ctx, GameServerMessageModel<GameServerRequestHeader> requestParam, GameUserChannel gameUserChannel) {
        this.requestParam = requestParam;
        this.ctx = ctx;
        this.gameUserChannel = gameUserChannel;
    }

    public GameServerRequestHeader getHeader() {
        return this.requestParam.getHeader();
    }

    public <T> T getRequestBody(Class<T> clazz) {
        ByteBuf byteBuf = this.requestParam.getBody();
        if (byteBuf.isReadable()) {
            // 读取剩余的可以读取的字节数量
            byte[] bytes = new byte[byteBuf.readableBytes()];
            byteBuf.readBytes(byteBuf);
            String json = new String(bytes, StandardCharsets.UTF_8);
            T data = JSON.parseObject(json, clazz);
            return data;
        }
        logger.warn("当前没有可以读取的数据，请检查接口是否使用正确");
        return null;
    }

}
